##    Copyright 2007 David Blewett
##
##   Licensed under the Apache License, Version 2.0 (the "License");
##   you may not use this file except in compliance with the License.
##   You may obtain a copy of the License at
##
##       http://www.apache.org/licenses/LICENSE-2.0
##
##   Unless required by applicable law or agreed to in writing, software
##   distributed under the License is distributed on an "AS IS" BASIS,
##   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
##   See the License for the specific language governing permissions and
##   limitations under the License.
## Author: David Blewett
## Contact: david@dawninglight.net

"""Top-level objects that return the imap object model."""
from threading import local
from urlparse import urlparse
from weakref import WeakValueDictionary
from mailbox import Mailbox
import commands


__all__ = [
    'Connection',
    'Session',
    ]

class Session(local):
    """
        Class to encapsulate a session on an IMAP4rev1 server.
    """
    def __init__(self, dsn, max_connections=5, debug=False):
        self.dsn = urlparse(dsn)
        self.max_connections = max_connections
        self.mailboxes = WeakValueDictionary()

    def select(self, mbox='INBOX'):
        if mbox in self.mailboxes:
            m = self.mailboxes[mbox]()
            if m is None:
                m = Mailbox(self.dsn, mbox)
                self.mailboxes[mbox] = m
            return m
        else:
            if len(self.mailboxes) < self.max_connections:
                m = Mailbox(self.dsn, mbox)
                self.mailboxes[mbox] = m
                return m
            #TODO: Add logic to remove a stale connection and create a new one

